package controllers;

import helpers.EmailHelper;
import helpers.IdUniqueHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.List;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import search.ArticleSearchEngine;
import systems.ConfigSystem;
import systems.Recently;
import systems.RecentlyTag;

import models.ArticleModel;
import models.CategoryModel;
import entities.Article;
import entities.ArticleSearch;
import entities.Category;
import entities.SiteConfig;
import entities.User;
import forms.ArticleForm;

public class ArticleDeleteServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String param = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		String[] params = param.split("/");
		
		String id = params[0];
		String authKey = "";
		if (params.length > 1) {
			authKey = params[1];
		}
		
		String language = (String) request.getAttribute("language");
		if (language == null || language.isEmpty()) {
			language = "en";
		}
		
		User user = (User) request.getAttribute("user_logged_in");
		
		ArticleModel articleModel = ArticleModel.getInstance();
		Article article = (Article) articleModel.getArticle(id);
		
		if (article == null || !article.getAuthKey().equals(authKey)) {
			response.sendRedirect("/msg/page-not-found");
			return;
		}
		
		if (article != null) {
			articleModel.delete(article);
			
			//Set search article
			ArticleSearchEngine.remove(id);
			
			//Remove recently cache
			Recently.remove(article);
			
			//Remove cache list
			articleModel.removeListCache(article);
			
			//remove cache my article
			articleModel.removeCacheMyArticle(article.getCreator(), language);
			
			//Send email to author
			String serverUrl = UrlHelper.getServerUrl(request);
			String serverName = UrlHelper.getDomainServer(request);
			String emails = user != null ? user.getUsername() : article.getEmail() ;
			String strUrl = serverUrl + "/print-email-delete?id="+article.getId()+"&title=" + article.getTitle();
			String strSubject = "[" + serverName + "] Your article with id " + article.getId() + " has been remove.";
			SiteConfig config = ConfigSystem.getConfigs();
			EmailHelper.sendMailFromUrl(serverName + " <" + config.getContactEmail() + ">", strSubject, strUrl, emails);
			
			article = null;
			
			//request.setAttribute("success", "Article has been removed!");
			response.sendRedirect("/profile/articles");
			return;
		}
	}
}
